package com.zzl.controller;

import com.zzl.entiey.LoginBody;
import com.zzl.entiey.User;
import com.zzl.mapper.LoginMapper;
import com.zzl.service.LoginService;
import com.zzl.util.Const;
import com.zzl.util.RedisUtil;
import com.zzl.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName: LoginController
 * @Description: GOOD
 * @author: ZZL
 * @date: 2021/7/5  9:38
 */
@RestController
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/user/login")
    public Result login(@RequestBody LoginBody loginBody){
          User user = new User();
          user.setUsername(loginBody.getUsername());
          user.setPassword(loginBody.getPassword());
        System.out.println(loginBody);
        String code = loginBody.getCode();
        System.out.println(code);
        if(code.equals(redisUtil.get(Const.CAPTCHA_KEY))){
        if ((loginService.login(user)).equals(Const.LOGIN_SUCCESS)){
            return Result.succ("登录成功");
        }else if((loginService.login(user)).equals(Const.WRONG_PASSWORD)){
            return Result.fail("密码错误");
        }
        }
        return Result.fail("登陆失败");
    }

    //校验验证码逻辑
    private Boolean validate(HttpServletRequest httpServletRequest){
        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("token");

        if(StringUtils.isBlank(code)||StringUtils.isBlank(key)){
            return false;
        }
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))){
            return false;
        }
        //一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY,key);
        return true;
    }

    @PostMapping("/user/register")
    public Result register(@RequestBody User user){
        if (loginService.register(user)){
            return Result.succ("注册成功");
        }else {
            return Result.fail("注册失败");
        }
    }

    @RequestMapping("/user/findAll")
    public Result findAllUser(){
        List<User> user = loginService.findAllUser();
        return Result.succ(user);
    }

    @RequestMapping("/user/deleted")
    public Result deletedUserByName(@RequestParam String userName){
        loginService.deletedUserByName(userName);
        return Result.succ("删除成功");
    }
}
